package com.inspector.app.ui.chat;

import static com.example.commen.utile.SingleClickUtilsKt.SingleClick;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.example.commen.net.easyHttp.EasyHttpManager;
import com.example.commen.net.easyHttp.model.HttpData;
import com.example.commen.resource.CommentContect;
import com.google.gson.Gson;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.Toaster;
import com.inspector.app.R;
import com.inspector.app.databinding.ActivityTaskChatBinding;
import com.inspector.app.di.network.api.UserInfoApi;
import com.inspector.app.listener.PhotoPickCallback;
import com.inspector.app.ui.base.BaseDJActivity;
import com.inspector.app.ui.chat.ImportUtils.MenuModeView;
import com.inspector.app.ui.chat.ImportUtils.SwitchKeyboardUtil;
import com.inspector.app.ui.chat.adapter.ChatAdapter;
import com.inspector.app.ui.chat.adapter.ExecuteAdapter;
import com.inspector.app.ui.chat.dialog.CustomPopWindow;
import com.inspector.app.ui.chat.dialog.TaskStatusDialog;
import com.inspector.app.ui.chat.entity.DataBean;
import com.inspector.app.ui.chat.entity.EntityMessageUtils;
import com.inspector.app.ui.chat.entity.FileEntity;
import com.inspector.app.ui.chat.entity.FileMessage;
import com.inspector.app.ui.chat.entity.HistoryMessageEntity;
import com.inspector.app.ui.chat.entity.Message;
import com.inspector.app.ui.chat.entity.MsgSendStatus;
import com.inspector.app.ui.chat.entity.ReceiveMessagesEntity;
import com.inspector.app.ui.chat.entity.SendMessage;
import com.inspector.app.ui.chat.entity.UserEntity;
import com.inspector.app.ui.chat.model.ActivityTaskChatModel;
import com.inspector.app.ui.chat.model.PeopleRequestManager;
import com.inspector.app.ui.chat.socket.SocketService;
import com.inspector.app.ui.chat.socket.SocketServiceListener;
import com.inspector.app.ui.chat.socket.UploadFile;
import com.inspector.app.ui.chat.socket.WebSocketUrlBuilder;
import com.inspector.app.ui.vo.TaskItem;
import com.inspector.app.ui.widget.ITitleBarLayout;
import com.inspector.app.ui.widget.ImportView;
import com.inspector.app.ui.widget.MorePanel;
import com.inspector.app.ui.widget.RecordButton;
import com.inspector.app.ui.chat.utils.ButtonUtils;
import com.inspector.app.util.CommenArgs;
import com.inspector.app.ui.chat.utils.KeyboardUtils;
import com.inspector.app.util.LogUtil;
import com.inspector.app.ui.chat.utils.MediaPlayerManager;
import com.inspector.app.ui.chat.utils.PhotoImagePicker;
import com.inspector.app.util.SharedPreferencesUtils;
import com.inspector.app.ui.chat.model.StateRequestManager;
import com.z.fileselectorlib.FileSelectorSettings;
import com.z.fileselectorlib.FileSelectorTheme;
import com.z.fileselectorlib.Objects.FileInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

public class TaskChatActivity extends BaseDJActivity implements View.OnClickListener
        , ImportView.onSendListener
        , RecordButton.OnFinishedRecordListener
        , ChatAdapter.OnItemListener
        , SocketServiceListener
        , MorePanel.OnMorePanelListener
        , StateRequestManager.Observer
        , PeopleRequestManager.PeopleRequestManagerObserver {
    private ActivityTaskChatBinding viewDataBinding;
    private ActivityTaskChatModel activityTaskChatModel;
    private ChatAdapter mAdapter;
    private List<ReceiveMessagesEntity> historyList = new ArrayList<>();
    private ExecuteAdapter executeAdapter;
    private SocketService socketService;
    private ActivityResultLauncher<Intent> video;
    private String taskId = "59";//任务id
    public static int mSenderId = -1;//个人id
    private UserInfoApi.UserInfo userInfo;//获取个人信息
    private boolean isOpen = false;//菜单是否打开
    private boolean isPermission = true;//默认有聊天权限

    private String statusTx = "";//任务状态文字藐视
    private String statusType = "1";//任务状态类型 1未开始 2进行中 3已完成 4手动终止
    private LinearLayoutManager mLinearLayout;
    private List<UserEntity> userDataList = new ArrayList<>();
    private TaskStatusDialog taskStatusDialog;
    //    private ChatInputHelper chatInputHelper;
    private SwitchKeyboardUtil switchKeyboardUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initStatusBar(false);
        viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_task_chat);
        viewDataBinding.setLifecycleOwner(this);
        activityTaskChatModel = new ViewModelProvider(this).get(ActivityTaskChatModel.class);

        //获取用户信息
        String userJson = SharedPreferencesUtils.getString(CommentContect.SpConstant.UserInfo);
        userInfo = GsonUtils.fromJson(userJson, CommenArgs.userInfo.getClass());
        //获取个人id
        mSenderId = userInfo != null ? userInfo.getId() : -1;


        TaskItem taskItem = (TaskItem) getIntent().getExtras().get("TaskItem");
        if (taskItem != null) {
            //获取权限
            isPermission = Boolean.TRUE.equals(taskItem.getHasAuth());

            //获取任务id
            taskId = taskItem.getId();
        }


        //获取长长连接地址
        String wsUrl = WebSocketUrlBuilder.buildWebSocketUrl(taskId, mSenderId + "", "8");
        // 初始化SocketService
        socketService = new SocketService(wsUrl, this);
        //开起轮询查询任务状态
        new StateRequestManager.Builder()
                .setLifecycleOwner(this)
                .setTaskId(taskId)
                .addObserver(this)
                .build();
        //开起轮询查询在线人数
        new PeopleRequestManager.Builder()
                .setLifecycleOwner(this)
                .setTaskId(taskId)
                .addObserver(this)
                .build();

        initView();
        observeData();

    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        viewDataBinding.titleBar.setTitle(getString(R.string.title_task), ITitleBarLayout.POSITION.LEFT);
        viewDataBinding.titleBar.getLeftIcon().setOnClickListener(this);
        viewDataBinding.titleBar.setRightIcon(R.mipmap.people_image);
        SingleClick(viewDataBinding.titleBar.getRightIcon(), view -> {
            setOpen();
        });
        viewDataBinding.drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
                open();

                executeAdapter.setData(userDataList);
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
                close();
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        viewDataBinding.drawerLayout.setScrimColor(Color.TRANSPARENT);

        viewDataBinding.menuRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        executeAdapter = new ExecuteAdapter();
        viewDataBinding.menuRv.setAdapter(executeAdapter);

        viewDataBinding.importView.setVisibility(isPermission ? View.VISIBLE : View.GONE);//有权限就展示键盘输入框无权限就隐藏

        viewDataBinding.importView.setOnSendListener(this);
        ImportView.getAudioButton().setOnFinishedRecordListener(this);
        ImportView.setMoreView(viewDataBinding.moreView);
        viewDataBinding.moreView.setOnOnMorePanelListener(this);

        mAdapter = new ChatAdapter(this);
        mLinearLayout = new LinearLayoutManager(this);
        mLinearLayout.setReverseLayout(true);
        viewDataBinding.chatRv.setLayoutManager(mLinearLayout);
        viewDataBinding.chatRv.setAdapter(mAdapter);
        mAdapter.setOnItemListener(this);

        setImportView();

        //跳转视频录制页面的Result
        video = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK) {
                // 处理结果
                Intent data = result.getData();
                if (data != null) {
                    // 从Intent中获取返回的数据
                    int type = data.getIntExtra("type", 0);
                    switch (type) {
                        case 1:
                            String imagePath = data.getStringExtra("image");
                            sendImageMessage(imagePath);
                            break;
                        case 2:
                            String videoPath = data.getStringExtra("video");
                            sendVedioMessage(videoPath);
                            break;
                    }

                }
            }
        });

    }

    @SuppressLint("ClickableViewAccessibility")
    private void setImportView() {
        switchKeyboardUtil = new SwitchKeyboardUtil(this);
        switchKeyboardUtil.setMenuViewHeightEqualKeyboard(true); //是否让菜单高度和键盘高度一样（首次可能会有误差）
        switchKeyboardUtil.setUseSwitchAnim(true);  //切换时是否使用动画（默认开启）
        switchKeyboardUtil.setUseMenuUpAnim(true); //菜单之间切换时从底部弹出 setUseSwitchAnim(true) 时才起作用
        switchKeyboardUtil.attachLifecycle(this); //所有设置设置这个之后才起效
        switchKeyboardUtil.setInputEditText(ImportView.getEdit()); //输入框（必须设置）
        switchKeyboardUtil.setAudioBtn(ImportView.getVoice());   //切换语音的按钮（不必设置）
        switchKeyboardUtil.setAudioTouchView(ImportView.getAudioButton());  //语音录制按钮（不必设置）
        switchKeyboardUtil.setMenuViewContainer(viewDataBinding.menuLayout);  //存放所有菜单的布局（必须设置）
        switchKeyboardUtil.setToggleMenuViews(new MenuModeView(ImportView.getAdd(), viewDataBinding.moreView));  //设置切换菜单的切换按钮和菜单布局（不必设置）
        switchKeyboardUtil.setOnKeyboardMenuListener(new SwitchKeyboardUtil.OnKeyboardMenuListener() {  //设置监听
            @Override
            public void onScrollToBottom() {//如果你需要让聊天内容在打开菜单或键盘时滑动到底部，则在此写代码
                scrollToBottom();
            }

            @Override
            public void onCallShowKeyboard() { //当调用显示键盘前回调

            }

            @Override
            public void onCallHideKeyboard() {  //当调用隐藏键盘前回调
            }

            @Override
            public void onKeyboardHide(int keyboardHeight) { //当键盘隐藏后回调

            }

            @Override
            public void onKeyboardShow(int keyboardHeight) { //当键盘显示后回调
                ImportView.getVoice().setImageResource(R.mipmap.selector_chat_voice_button);
                ImportView.getAdd().setImageResource(R.mipmap.more_image);
            }


            @Override
            public void onShowMenuLayout(View layoutView) { //当显示某个菜单布局(即 MenuModeView.toggleViewContainer )时回调
                ImportView.getVoice().setImageResource(layoutView == viewDataBinding.importView.getAudioButton() ? R.mipmap.ic_keyboard : R.mipmap.selector_chat_voice_button);
                ImportView.getAdd().setImageResource(layoutView == viewDataBinding.moreView ? R.mipmap.ic_keyboard : R.mipmap.more_image);
            }

            @Override
            public void onHideMenuViewContainer() {  //当收起菜单时回调这个方法
                ImportView.getVoice().setImageResource(R.mipmap.selector_chat_voice_button);
                ImportView.getAdd().setImageResource(R.mipmap.more_image);
            }
        });
        viewDataBinding.chatRv.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                switchKeyboardUtil.hideMenuAndKeyboard();
            }
            return false;
        });
        viewDataBinding.chatRvLayout.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                switchKeyboardUtil.hideMenuAndKeyboard();
            }
            return false;
        });
        //这个是保持消息平滑移动的关键
        View.OnLayoutChangeListener onLayoutChangeListener = (v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> scrollToBottom();
        viewDataBinding.chatRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState != RecyclerView.SCROLL_STATE_IDLE) {
                    recyclerView.removeOnLayoutChangeListener(onLayoutChangeListener);
                } else {
                    recyclerView.addOnLayoutChangeListener(onLayoutChangeListener);
                }
            }
        });
    }


    private void scrollToBottom() {
        if (getLifecycle().getCurrentState() == Lifecycle.State.RESUMED && viewDataBinding.chatRv.getAdapter() != null) {
            viewDataBinding.chatRv.scrollToPosition(0);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (switchKeyboardUtil.onKeyDown(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void open() {
        viewDataBinding.drawerLayout.openDrawer(Gravity.RIGHT);
        isOpen = true;
        //打开侧栏的时候收起键盘
        KeyboardUtils.hideSoftInput(this);
    }

    private void close() {
        viewDataBinding.drawerLayout.closeDrawer(Gravity.RIGHT);
        isOpen = false;
    }

    private void setOpen() {
        if (isOpen) {
            close();
        } else {
            open();
        }
    }


    @Override
    public void onConnected() {
        viewDataBinding.titleBar.getMiddleTitle().setVisibility(View.GONE);
    }

    @Override
    public void onMessageReceived(String message) {
        if (message != null) {
            ReceiveMessagesEntity historyMessageEntity = GsonUtils.fromJson(message, ReceiveMessagesEntity.class);
            if (historyMessageEntity != null) {
                if (historyMessageEntity.getMsgType() == 3) {
                    mAdapter.setUpdateRevocationMessage(historyMessageEntity);
                } else {
                    String message1 = historyMessageEntity.getMessage();
                    try {
                        JSONObject jsonObject = new JSONObject(message1);
                        String id = jsonObject.optString("id");
                        if (id.isEmpty()) {//接收到的消息
                            EntityMessageUtils.setAudioTimeAndThumbnail(historyMessageEntity);
                            mAdapter.setUpdateMessage(historyMessageEntity);
                            mLinearLayout.scrollToPosition(0);
                        } else {//我发送的消息
                            historyMessageEntity.setSendStatus(MsgSendStatus.SENT);//消息状态
                            EntityMessageUtils.setAudioTimeAndThumbnail(historyMessageEntity);
                            mAdapter.setUpdateCallBackMessage(historyMessageEntity);
                            Log.e("TaskChatActivity", "我发送的消息");
                        }
                    } catch (JSONException e) {
                        Log.e("TaskChatActivity", "解析json报错", e);
                    }
                }

            }

        }
    }


    @Override
    public void onDisconnected() {
        viewDataBinding.titleBar.getMiddleTitle().setVisibility(View.VISIBLE);
        viewDataBinding.titleBar.setTitle(getString(R.string.title_tautology), ITitleBarLayout.POSITION.MIDDLE);
    }

    @Override
    public void onError() {
        viewDataBinding.titleBar.getMiddleTitle().setVisibility(View.VISIBLE);
        viewDataBinding.titleBar.setTitle(getString(R.string.title_state), ITitleBarLayout.POSITION.MIDDLE);
    }

    private void observeData() {
        showProgress("加载聊天记录");
        activityTaskChatModel.getHistoryList().observe(this, historyMessageEntities -> {
            if (historyMessageEntities != null) {
                historyList.clear();
                for (int i = 0; i < historyMessageEntities.size(); i++) {
                    HistoryMessageEntity historyMessageEntity = historyMessageEntities.get(i);
                    ReceiveMessagesEntity historyToReceive = EntityMessageUtils.getHistoryToReceive(historyMessageEntity);
                    historyList.add(historyToReceive);
                }
                mAdapter.setData(historyList);

            }
            dismissProgress();
        });
        activityTaskChatModel.getHistoryMessage(this, taskId);
    }


    private SendMessage getBaseReceiveMessage(int msgType) {
        SendMessage mMessgae = new SendMessage();
        mMessgae.setSendUserName(userInfo.getRealname());//名字
        mMessgae.setSendHeadPic(userInfo.getHeadUrl());//头像
        mMessgae.setSendUserId(mSenderId);//发送人id
        mMessgae.setTaskId(taskId);//任务id
        mMessgae.setMsgType(msgType >= 5 && msgType <= 10 ? 2 : 0);//消息类型:0.普通消息 2.地图消息
        mMessgae.setMsgDetail(msgType);//消息类型:1.文字 2.图片 3.音频 4.视频 5.点
        return mMessgae;

    }


    @Override
    public void onClick(View view) {
        if (ButtonUtils.isFastDoubleClick(view.getId())) return;
        if (view.getId() == viewDataBinding.titleBar.getLeftIcon().getId()) {
            finish();
        }

    }

    @Override
    public void onSend(String content) {
        if (!TextUtils.isEmpty(content))
            sendTextMsg(content);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FileSelectorSettings.FILE_LIST_REQUEST_CODE && resultCode == FileSelectorSettings.BACK_WITH_SELECTIONS) {
            assert data != null;
            Bundle bundle = data.getExtras();
            assert bundle != null;
            ArrayList<String> FilePathSelected = bundle.getStringArrayList(FileSelectorSettings.FILE_PATH_LIST_REQUEST);
            for (String file_path : FilePathSelected) {
                Log.v("file_sel", file_path);
                File file = new File(file_path);
                if (file.isFile()) {
                    sendFileMessage(file_path, file.getName());
                }

            }
        } else {
            PhotoImagePicker.getInstance().onActivityResult(this, requestCode, resultCode, data);
        }
    }

    @Override
    public void onFinishedRecord(String audioPath, int time) {
        LogUtil.d("录音结束回调" + audioPath);
        File file = new File(audioPath);
        if (file.exists()) {
            sendAudioMessage(audioPath);
        }
    }


    /**
     * 展示图片
     *
     * @param dataBean
     * @param position
     */
    @Override
    public void showImageListener(DataBean dataBean, int position) {
        Intent intent = new Intent(this, PictureActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("DataBean", dataBean);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 展示视频
     *
     * @param dataBean
     * @param position
     */
    @Override
    public void showVideoListener(DataBean dataBean, int position) {
        Intent intent = new Intent(this, VideoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("DataBean", dataBean);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 展示点
     *
     * @param bot
     * @param position
     */
    @Override
    public void showBotListener(String bot, int position) {

    }

    /**
     * 展示文件
     * 目前只能跳转浏览器去查看在线文档
     *
     * @param url
     * @param position
     */
    @Override
    public void showFileListener(String url, int position) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri contentUrl = Uri.parse(url);
        intent.setData(contentUrl);
        startActivity(intent);
    }

    /**
     * 播放音频
     *
     * @param animation
     * @param url
     * @param position
     * @param isPlay
     */
    private boolean isPlay = false;

    @Override
    public void startAudioListener(AnimationDrawable animation, String url, int position) {
        if (isPlay) {
            isPlay = false;
            // 停止播放
            // 如果动画正在运行，先停止它
            if (animation.isRunning()) {
                animation.stop();
            }
            // 将动画重置到第一帧
            animation.selectDrawable(0);
            MediaPlayerManager.release();

        } else {
            isPlay = true;
            // 声音播放动画
            animation.start();
            // 播放录音
            MediaPlayerManager.playSound(url, mp -> {
                isPlay = false;
                // 如果动画正在运行，先停止它
                if (animation.isRunning()) {
                    animation.stop();
                }
                // 将动画重置到第一帧
                animation.selectDrawable(0);
                MediaPlayerManager.release();
            });

        }
    }

    /**
     * 长按撤回消息
     *
     * @param entity
     * @param position
     */
    @Override
    public void OnItemLongListener(ReceiveMessagesEntity entity, View view, int position) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.revocation_layout, null);

        // 创建CustomPopWindow实例
        CustomPopWindow mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) // 显示大小
                .create();


        // 获取PopupWindow的宽度
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = contentView.getMeasuredWidth();
        int popupHeight = contentView.getMeasuredHeight();

        // 获取view的宽度，考虑到padding的影响
        int viewWidth = view.getWidth() - view.getPaddingLeft() - view.getPaddingRight();

        // 计算PopupWindow相对于view的水平偏移量
        int offsetX = (viewWidth - popupWidth) / 2;

        // 计算PopupWindow相对于view的垂直偏移量
        int offsetY = -(popupHeight + view.getHeight()); // 垂直居中可能需要调整
        // 显示PopupWindow在触发View的正上方，且水平居中对齐
        mListPopWindow.showAsDropDown(view, offsetX, offsetY, Gravity.CENTER_HORIZONTAL | Gravity.TOP);

        // 设置根布局的点击事件
        RelativeLayout rootLayout = contentView.findViewById(R.id.root_layout);
        rootLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mListPopWindow.dissmiss();
                activityTaskChatModel.getRevocationMessage(TaskChatActivity.this, entity.getMsgId(), new HttpCallback<HttpData<String>>() {
                    @Override
                    public void onSucceed(HttpData<String> result) {
                        if (200 == result.getCode()) {
                            Toaster.show("撤回成功");
                        } else {
                            Toaster.show(result.getMessage());
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        Toaster.show("撤回失败");
                    }


                });
            }
        });


    }

    /**
     * 重新发送
     *
     * @param entity
     * @param position
     */
    @Override
    public void OnItemResendListener(ReceiveMessagesEntity entity, String file, int position) {
        if (entity != null) {
//            entity.setSendStatus(MsgSendStatus.SENDING);
//            mAdapter.setUpdateCallBackMessage(entity);
            SendMessage receiveToSend = EntityMessageUtils.getReceiveToSend(entity);
//            uploadManager(receiveToSend, file, receiveToSend.getMsgDetail());
            Log.i("OnItemResendListener", "重新发送数据" + new Gson().toJson(receiveToSend) + "                   file:" + file);
        }

    }


    //文本消息
    private void sendTextMsg(String content) {
        //构建文本消息
        SendMessage mMessgaeText = getBaseReceiveMessage(1);
        Message message = new Message();
        message.setContent(content);
        message.setId(UUID.randomUUID().toString());
        mMessgaeText.setMessage(message);
        ReceiveMessagesEntity sendToReceive = EntityMessageUtils.getSendToReceive(mMessgaeText);
        sendToReceive.setSendStatus(MsgSendStatus.SENDING);
        mAdapter.setUpdateMessage(sendToReceive);
        mLinearLayout.scrollToPosition(0);
        uploadManager(mMessgaeText, "", 1);
    }


    //图片消息
    private void sendImageMessage(String image) {
        SendMessage mMessgae = getBaseReceiveMessage(2);
        Message message = new Message();
        message.setContent(image);
        message.setId(UUID.randomUUID().toString());
        mMessgae.setMessage(message);
        ReceiveMessagesEntity sendToReceive = EntityMessageUtils.getSendToReceive(mMessgae);
        sendToReceive.setSendStatus(MsgSendStatus.SENDING);
        mAdapter.setUpdateMessage(sendToReceive);
        mLinearLayout.scrollToPosition(0);
        uploadManager(mMessgae, image, 2);

    }


    //视频消息
    private void sendVedioMessage(String media) {
        SendMessage mMessgae = getBaseReceiveMessage(4);
        Message message = new Message();
        message.setContent(media);
        message.setId(UUID.randomUUID().toString());
        mMessgae.setMessage(message);
        ReceiveMessagesEntity sendToReceive = EntityMessageUtils.getSendToReceive(mMessgae);
        sendToReceive.setSendStatus(MsgSendStatus.SENDING);
        mAdapter.setUpdateMessage(sendToReceive);
        mLinearLayout.scrollToPosition(0);
        uploadManager(mMessgae, media, 4);
    }


    //语音消息
    private void sendAudioMessage(String path) {
        SendMessage mMessgae = getBaseReceiveMessage(3);
        Message message = new Message();
        message.setContent(path);
        message.setId(UUID.randomUUID().toString());
        mMessgae.setMessage(message);
        ReceiveMessagesEntity sendToReceive = EntityMessageUtils.getSendToReceive(mMessgae);
        sendToReceive.setSendStatus(MsgSendStatus.SENDING);
        mAdapter.setUpdateMessage(sendToReceive);
        mLinearLayout.scrollToPosition(0);
        uploadManager(mMessgae, path, 3);
    }

    //点消息
    private void sendBotMessage(String bot) {
        SendMessage mMessgae = getBaseReceiveMessage(5);
        Message message = new Message();
        message.setContent(bot);
        message.setId(UUID.randomUUID().toString());
        mMessgae.setMessage(message);
        ReceiveMessagesEntity sendToReceive = EntityMessageUtils.getSendToReceive(mMessgae);
        sendToReceive.setSendStatus(MsgSendStatus.SENDING);
        mAdapter.setUpdateMessage(sendToReceive);
        mLinearLayout.scrollToPosition(0);
        uploadManager(mMessgae, "", 5);
    }

    //文件消息
    private void sendFileMessage(String file, String name) {
        SendMessage mMessgae = getBaseReceiveMessage(11);
        FileMessage message = new FileMessage();
        FileEntity fileEntity = new FileEntity();
        fileEntity.setName(name);
        fileEntity.setUrl(file);
        message.setContent(fileEntity);
        message.setId(UUID.randomUUID().toString());
        mMessgae.setMessage(message);
        ReceiveMessagesEntity sendToReceive = EntityMessageUtils.getSendToReceive(mMessgae);
        sendToReceive.setSendStatus(MsgSendStatus.SENDING);
        mAdapter.setUpdateMessage(sendToReceive);
        mLinearLayout.scrollToPosition(0);
        uploadManager(mMessgae, file, 11);
    }


    private void uploadManager(SendMessage mMessgae, String file, int type) {
        //消息类型:1.文字 2.图片 3.音频 4.视频 5.点 11.文件消息
        switch (type) {
            case 1:
            case 5:
                if (socketService.isConnected()) {
                    socketService.sendMessage(new Gson().toJson(mMessgae));//文字以及点消息直接发送服务器
                } else {
                    ReceiveMessagesEntity sendToReceive = EntityMessageUtils.getSendToReceive(mMessgae);
                    sendToReceive.setSendStatus(MsgSendStatus.FAILED);   //消息失败状态
                    mAdapter.setUpdateCallBackMessage(sendToReceive);
                    Log.i("uploadManager", "发送文字但是长连接断开导致的发送失败" + new Gson().toJson(mMessgae));
                    showDialogs("未连接请重新连接", view -> {
                        taskStatusDialog.dismiss();
                        socketService.scheduleReconnect();//重连
                    });
                }
                break;
            case 2:
            case 3:
            case 4:
            case 11:
                new UploadFile().uploadFile(new File(file)).setUploadFileCallBack(new UploadFile.UploadFileCallBack() {
                    /**
                     * 上传成功后更新单条状态并且更新列表
                     * @param data
                     */
                    @Override
                    public void resultFile(EasyHttpManager.UpLoadFileResult.Data data) {
                        if (type == 4 || type == 3) {
                            Message message = (Message) mMessgae.getMessage();
                            message.setContent(data.getDownUrl());
                        } else if (type == 11) {
                            FileMessage fileMessage = (FileMessage) mMessgae.getMessage();
                            FileEntity content = fileMessage.getContent();
                            content.setUrl(data.getDownUrl());
                            fileMessage.setContent(content);
                        } else {
                            Message message = (Message) mMessgae.getMessage();
                            message.setContent(data.getPicURL());
                        }
                        if (socketService.isConnected()) {
                            socketService.sendMessage(new Gson().toJson(mMessgae));
                            Log.i("uploadManager", "我发送的消息" + new Gson().toJson(mMessgae));
                        } else {
                            ReceiveMessagesEntity sendToReceive = EntityMessageUtils.getSendToReceive(mMessgae);
                            sendToReceive.setSendStatus(MsgSendStatus.FAILED);   //消息失败状态
                            mAdapter.setUpdateCallBackMessage(sendToReceive);
                            showDialogs("未连接请重新连接", view -> {
                                taskStatusDialog.dismiss();
                                socketService.scheduleReconnect();//重连
                            });
                            Log.i("uploadManager", "上传文件成功后长连接断开" + new Gson().toJson(mMessgae));
                        }
                    }

                    /**
                     * 上传失败更新单条状态并且更新列表
                     */
                    @Override
                    public void error() {
                        ReceiveMessagesEntity sendToReceive = EntityMessageUtils.getSendToReceive(mMessgae);
                        sendToReceive.setSendStatus(MsgSendStatus.FAILED);   //消息失败状态
                        mAdapter.setUpdateCallBackMessage(sendToReceive);
                        Log.i("uploadManager", "上传失败导致的发送失败" + new Gson().toJson(mMessgae));
                    }
                });
                break;


        }

    }


    /**
     * 打开图片选择
     */
    @Override
    public void showImage() {
        PhotoImagePicker.getInstance().startGallery(this, new PhotoPickCallback() {
            @Override
            public void onCanceled() {
                //用户取消
            }

            @Override
            public void onPickImage(@Nullable Uri imageUri) {
                sendImageMessage(imageUri.getPath());
            }

            @Override
            public void onPickVideo(@Nullable Uri imageUri) {
                sendVedioMessage(imageUri.getPath());
            }

            @Override
            public void onPickFile(@Nullable Uri imageUri) {

            }

            @Override
            public void onError(String e) {
                Log.i("TAG", "onError: " + e.toString());

            }
        });
    }

    /**
     * 拍摄视频
     */
    @Override
    public void showCamera() {
        Intent intent = new Intent(this, VideoRecorderActivity.class);
        video.launch(intent);
    }

    /**
     * 位置
     */
    @Override
    public void showLocation() {
//        new MapDialog().newInstance().setData("").showDialog(getSupportFragmentManager());//位置地图
    }

    /**
     * 文件
     */
    @Override
    public void showFile() {
        FileSelectorTheme theme = new FileSelectorTheme();
        theme.setTopToolBarTitleColor("#ffffff")
                .setThemeColor("#1C1C1C");
        FileSelectorSettings settings = new FileSelectorSettings();
        settings.setTheme(theme);
        settings.setRootPath(FileSelectorSettings.getSystemRootPath())
                .setMaxFileSelect(1)
                .setTitle("长按请选择文件")
                .setFileTypesToSelect(FileInfo.FileType.Unknown)//选择自定义后缀的文件此处参数需为Unknown/File
                .setFileTypesToShow(".pdf", ".docx")//自定义可见的文件后缀
                .setCustomizedIcons(new String[]{".pdf", ".docx"}, this, R.mipmap.pdf_image, R.mipmap.docx_image)//自定义文件图标
                .show(this);
    }

    /**
     * 标会
     */
    @Override
    public void showPlotting() {

    }

    /**
     * @param data 任务状态: -1请求失败 1未开始 2进行中 3已完成 4手动终止
     */
    //轮询任务状态
    @Override
    public void onDataReceived(String data) {
        statusType = data;
        Log.i("TaskChatActivity", "任务状态" + data);
        if (data.equals("-1")) return;
        if (!data.equals("2")) {
            if (data.equals("1")) {
                statusTx = "任务未开始";
            } else if (data.equals("3")) {
                statusTx = "任务已完成";
            } else if (data.equals("4")) {
                statusTx = "任务手动终止";
            }
            showDialogs(statusTx, view -> {
                taskStatusDialog.dismiss();
                finish();
            });
        }

    }


    private void showDialogs(String st, View.OnClickListener listener) {
        if (taskStatusDialog == null) {
            taskStatusDialog = new TaskStatusDialog(this).setContent(st).setConfirmListener(listener);
        }
        if (!taskStatusDialog.isShowing()) {
            taskStatusDialog.show();
        }
    }

    @Override
    public void onPeopleDataReceived(List<UserEntity> data) {
        if (data != null) {
            Log.i("TaskChatActivity", "获取人物");
            userDataList.clear();
            userDataList.addAll(data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
        if (socketService != null) {
            socketService.close();
        }
        if (taskStatusDialog != null && taskStatusDialog.isShowing()) {
            taskStatusDialog.dismiss();
        }
    }


}
